<template>
  <div class="flex items-center space-x-2">
    <!-- 语言切换按钮 -->
    <button
      v-for="lang in languages"
      :key="lang.value"
      @click="selectLanguage(lang.value)"
      class="px-4 py-2 rounded-md transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2"
      :class="[
        selectedLanguage === lang.value
          ? 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500'
          : 'bg-gray-200 text-gray-700 hover:bg-gray-300 focus:ring-gray-400',
      ]"
    >
      {{ lang.label }}
    </button>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useSystemStore } from "@/store";
const systemStore = useSystemStore();
const { lang } = storeToRefs(systemStore);
const { setLang } = systemStore;
import { getSystemLocale } from "@/i18n";

// 定义支持的语种
const languages = [
  { label: "中文", value: "zh" },
  { label: "English", value: "en" },
];

// 选中的语言
const selectedLanguage = ref(lang.value);

// 从 localStorage 初始化语言
onMounted(() => {
  if (!lang) {
    setLang(getSystemLocale());
  }
});

// 选择语言
const selectLanguage = (lang) => {
  selectedLanguage.value = lang;
  setLang(lang);
  emit("change", lang);
};

// 定义事件
const emit = defineEmits(["change"]);

// 暴露当前语言给父组件
defineExpose({
  getCurrentLanguage: () => selectedLanguage.value,
});
</script>

<style scoped>
/* 添加平滑过渡效果 */
button {
  transition-property: background-color, color, transform;
}
button:active {
  transform: scale(0.98);
}
</style>
